package cl.uchile.sketchpad.persistance.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cl.uchile.sketchpad.persistance.model.SubjectVersion;

@Repository
public class SubjectVersionDaoImpl implements SubjectVersionDao {

	@PersistenceContext
	private EntityManager em;
	
	@Override
	@Transactional(readOnly = true)
	public List<SubjectVersion> getAll() {
		TypedQuery<SubjectVersion> q = em.createQuery("from SubjectVersion", SubjectVersion.class);
		return q.getResultList();
	}

	@Override
	@Transactional(readOnly = true)
	public SubjectVersion findById(Integer id) {
		TypedQuery<SubjectVersion> q = em.createQuery("from SubjectVersion s where s.id=:subjectVersionId", SubjectVersion.class);
		q.setParameter("subjectVersionId", id);
		try {
			return q.getSingleResult();
		} catch ( Exception e ) {
			e.printStackTrace(System.err);
		}
		return null;
	}

	@Override
	@Transactional
	public void persist(SubjectVersion subjectVersion) {
		em.persist(subjectVersion);
	}
	
	@Override
	@Transactional(readOnly = true)
	public SubjectVersion findGuestSubject() {
		return em.find(SubjectVersion.class, GUEST_SUBJECT_ID);
	}

}
